import config from '@/common/environment.js';
const tioServer = config.TIO_SERVER;

const ping = "{'code':'0'}";
const ready = "{'code':'1'}";


var WsRequest = {
	status: null,
	lockReconnect: false,
	url: tioServer,
	isConnected: false,
	//是否主动关闭
	closeByUser: false,
	timeout: 5000,
	timeoutTask:null,
	reconnectTimeoutTask: null,
	socket: null,
	  //初始话
	connectSocketInit:function(url){
		console.log("初始化webSocket链接======地址:"+url);
		this.url=url;
		this.socket = uni.connectSocket({
			url: url,
			success(data) {
				console.log("Tio初始化连接成功");
			},
		});
		this.socket.onOpen=()=>{
			this.send(ready);
			// 清除重连定时器
			if (this.reconnectTimeoutTask) {
				clearTimeout(this.reconnectTimeoutTask);
			}
			// 开启检测
			this.reset();
		};
			
		// 如果希望websocket连接一直保持，在close或者error上绑定重新连接方法。
		this.socket.onclose = () => {
			if(!this.closeByUser){
			  this.isConnected = false;
			  this.reconnect();
			}
		};
		
		this.socket.onerror = () => {
			this.isConnected = false;
			this.reconnect();
		};
			
		this.socket.onmessage = (event) => {
			const data = event.data;
			const sendInfo = JSON.parse(data);
			// 真正的消息类型
			//console.log("监听到服务器端返回的信息",sendInfo);
			if (sendInfo.code ==2) {
				this.onmessage(sendInfo.message);
			}
			//接受任何消息都说明当前连接是正常的
			reset();
	  	};
	},
	  
	  //发送状态
	send:function(value){
		if (this.socket.readyState === 1) {
			// console.log("发送内容",value);
			this.socket.send(value);
		} 
		else {
			this.reset();
			this.reconnect();
		}
	},
	  
	  //reset和start方法主要用来控制心跳的定时。
	reset:function(){
		let that=this;
	  	// 清除定时器重新发送一个心跳信息
	  	if (that.timeoutTask) {
	  	  clearTimeout(that.timeoutTask);
	  	}
		//这里发送一个心跳，后端收到后，返回一个心跳消息，
	  	that.timeoutTask = setTimeout(() => {
	  	   that.send(ping); //onmessage拿到返回的心跳就说明连接正常
	  	},that.timeout);
	},
	  
	  // 重连
	reconnect:function(){
		  let that=this;
	      console.log("lockReconnect", that.lockReconnect);
	      // 防止多个方法调用，多处重连
	      if (that.lockReconnect) {
	        return;
	      }
	      that.lockReconnect = true;
	      //没连接上会一直重连，设置延迟避免请求过多
	      that.reconnectTimeoutTask = setTimeout(() => {
	        // 重新连接
	        that.connectSocketInit(that.url);
	        that.lockReconnect = false;
	      }, 4000);
	},
	  
	  //收到消息，这里会被重写覆盖
	onmessage:function(message){
	    console.log(message);
	},
};

export default {
	WsRequest:WsRequest
}	
